import {
    _decorator, Component, Node, Size, Sprite, SpriteFrame, UITransform, ParticleSystem2D, v3,
    find, tween, TweenEasing, Color,
    Vec3, Widget, NodeEventType, EventTouch, Vec2
} from 'cc';
import {XiaoXiaoItemPosition} from "db://assets/scripts/xiaoxiao/XiaoXiaoItemPosition";
import {XiaoXiaoGame} from "db://assets/scripts/xiaoxiao/XiaoXiaoGame";
import {XiaoXiaoGameManey} from "db://assets/scripts/xiaoxiao/XiaoXiaoGameManey";

const {ccclass, property} = _decorator;

@ccclass('CandyItem')
export class CandyItem extends Component {

    sprite: Sprite = null;
    particleSystem: ParticleSystem2D = null;
    selectIcon: Sprite = null;
    xaoxiaoGame: XiaoXiaoGame | XiaoXiaoGameManey;
    row: number;
    column: number;


    start() {
        this.xaoxiaoGame = find("XiaoXiaoGame").getComponent(XiaoXiaoGame);
        if (!this.xaoxiaoGame) {
            this.xaoxiaoGame = find("XiaoXiaoGame").getComponent(XiaoXiaoGameManey);
        }

        this.addTouch();

    }

    update(deltaTime: number) {
        if (this.xaoxiaoGame.touchTarget) {
            this.xaoxiaoGame.currentTouchStart += deltaTime;
        }
    }

    private addTouch() {
        this.node.on(NodeEventType.TOUCH_START, this.touchStart, this);
        this.node.on(NodeEventType.TOUCH_MOVE, this.touchMove, this);
        this.node.on(NodeEventType.TOUCH_CANCEL, this.touchCancel, this);
        this.node.on(NodeEventType.TOUCH_END, this.touchEnd, this);
    }

    private touchStart(event: EventTouch) {
        if (!this.xaoxiaoGame.isGame) return;
        if (this.xaoxiaoGame.isClick) return;
        console.log("touchStart")
        this.xaoxiaoGame.touchTarget = event.target;
        this.xaoxiaoGame.currentTouchStart = 0;
        this.xaoxiaoGame.touchStartPosition = event.getLocation();

    }

    private touchMove(event: EventTouch) {
        if (!this.xaoxiaoGame.isGame) return;
        if (this.xaoxiaoGame.isClick) return;
        if (this.xaoxiaoGame.touchTarget == null) return;
        if (this.xaoxiaoGame.touchCandyItemOne != null) return;
        let touchTarget: CandyItem = this.xaoxiaoGame.touchTarget.getComponent(CandyItem);


        let moveLocation = event.getLocation();
        let offsetX = moveLocation.x - this.xaoxiaoGame.touchStartPosition.x;
        let offsetY = moveLocation.y - this.xaoxiaoGame.touchStartPosition.y;

        if (Math.abs(offsetX) < 2
            && Math.abs(offsetY) < 2) {
            return;
        }
        console.log("touchMove")


        let nextTarget: XiaoXiaoItemPosition = null;
        // x轴滑动
        if (Math.abs(offsetX) > Math.abs(offsetY)) {
            if (offsetX > 0) {
                // 右移
                nextTarget = this.xaoxiaoGame.getNextSquareRowColumn(touchTarget.row, touchTarget.column, 2);
            } else {
                // 左移
                nextTarget = this.xaoxiaoGame.getNextSquareRowColumn(touchTarget.row, touchTarget.column, 1);
            }
        } else {
            // y轴滑动
            if (offsetY > 0) {
                // 上划
                nextTarget = this.xaoxiaoGame.getNextSquareRowColumn(touchTarget.row, touchTarget.column, 3);
            } else {
                // 下划
                nextTarget = this.xaoxiaoGame.getNextSquareRowColumn(touchTarget.row, touchTarget.column, 4);
            }
        }
        if (nextTarget != null) {
            this.xaoxiaoGame.touchTarget.getComponent(CandyItem).touch();
            nextTarget.item.getComponent(CandyItem).getComponent(CandyItem).touch();
        }
        this.xaoxiaoGame.touchTarget = null;
    }

    private touchCancel(event: EventTouch) {
        this.xaoxiaoGame.touchTarget = null;
    }

    private touchEnd(event: EventTouch) {
        if (!this.xaoxiaoGame.isGame) return;
        if (this.xaoxiaoGame.isClick) return;
        console.log("touchEnd")

        if (this.xaoxiaoGame.touchTarget != null) {
            this.xaoxiaoGame.touchTarget.getComponent(CandyItem).touch();
            this.xaoxiaoGame.touchTarget = null;
        }
    }


    public setInfo(row: number, column: number) {
        this.row = row;
        this.column = column;
    }

    public init(spriteFrame: SpriteFrame,
                arrayItem: XiaoXiaoItemPosition,
                columnWidth: number,
                space: number,
                parentWidth: number,
                parentHeight: number,
                externalSpaceWidth: number,
                row: number,
                column: number,
                type: number
    ) {
        let columnWidthSpace = columnWidth - space;
        this.sprite = this.node.children[0].getComponent(Sprite);
        this.particleSystem = this.node.children[1].getComponent(ParticleSystem2D);
        this.selectIcon = this.node.children[2].getComponent(Sprite);
        this.selectIcon.node.active = false;
        this.particleSystem.node.active = false;
        this.row = row;
        this.column = column;
        let sprite = this.node.children[0];

        let interval = 10;
        if (type === 2) {
            interval = 4;
        }


        this.getComponent(UITransform).contentSize = new Size(columnWidth, columnWidth);
        let positionX = (-(parentWidth / 2)) + ((columnWidth + interval) * arrayItem.column) + columnWidth / 2;
        let positionY = (parentHeight / 2) - ((columnWidth + interval) * arrayItem.row);
        this.node.position = v3(positionX, positionY, 0);


        sprite.getComponent(Sprite).spriteFrame = spriteFrame;
        if ((columnWidthSpace / spriteFrame.rect.width) * spriteFrame.rect.height > columnWidthSpace) {
            sprite.getComponent(UITransform).contentSize = new Size(Math.floor((columnWidthSpace / spriteFrame.rect.height) * spriteFrame.rect.width),
                columnWidthSpace);
        } else {
            sprite.getComponent(UITransform).contentSize = new Size(columnWidthSpace,
                Math.floor((columnWidthSpace / spriteFrame.rect.width) * spriteFrame.rect.height));
        }


        // 粒子系统赋值
        this.particleSystem.spriteFrame = spriteFrame;
    }

    public playDestroy() {
        this.particleSystem.node.active = true;
        let duration = this.particleSystem.duration;
        this.particleSystem.resetSystem();
        this.scheduleOnce(() => {
            this.particleSystem.node.active = false;
            this.scheduleOnce(() => {
                this.node.destroy();
            }, 1);


            this.node.destroy();
        }, duration);

    }

    private async touch() {
        console.log("触摸", this.row, this.column)
        if (this.xaoxiaoGame.isClick === false) {
            await this.xaoxiaoGame.touchCandyItemClick(this);
        }
    }

    public setSelect() {
        this.selectIcon.node.active = true;
        let alpha = 255;
        let easingStr: TweenEasing = "elasticOut";
        let duration: number = 1;


        if (this.selectIcon.color.a === 255) {
            alpha = 0;
            easingStr = "linear";
            duration = 0.4;
        }
        let newColor = new Color(this.selectIcon.color.r, this.selectIcon.color.g, this.selectIcon.color.b,
            alpha);
        tween(this.selectIcon)
            .to(duration, {color: newColor}, {
                easing: easingStr,
            })
            .call(() => {
                if (this.selectIcon.node.active) {
                    this.setSelect();
                }
            })
            .start()
    }

    public hideSelect() {
        this.selectIcon.node.active = false;
    }

}


